#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
else
   echo "Unknown OS"
fi

# APP_INSTALL_NAME="voxcpm"
APP_TARGET_DIR_NAME="voxcpm"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
# source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/env"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo "$CURRENT_APP_PATH"
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: $CURRENT_APP_PATH"
else
    echo "Error, App Dir dose not exist, please retry. $CURRENT_APP_PATH"
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_REPO_URL="${GIT_HOST}/OpenBMB/VoxCPM"

export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:30"

cd "$CURRENT_APP_PATH"
CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi
# INDEX_TTS_ENV_NAME=$APP_INSTALL_NAME
export PYTHON_VER_ENV=3.12
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV pip=25.2 -y

echo "lmdprogress:40"

install_torch() {
    if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        # conda_run_pip_install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
        source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
        # conda_run_conda_forge_install ffmpeg
    elif current_os_is_windows; then
        source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
        # check_ffmpeg_and_install_win
    fi
}
install_torch

echo "lmdprogress:50"
conda_run_pip_install -e .

echo "lmdprogress:67"
conda_run_pip_install huggingface_hub==0.35.1 hf_xet modelscope

echo "lmdprogress:75"

# download models
if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

echo "lmdprogress:80"

export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home"
export MODELSCOPE_HOME="$CURRENT_APP_PATH/tmp_modelscope_home"
export MODELSCOPE_CACHE="$CURRENT_APP_PATH/tmp_modelscope_cache"

conda_run_cmd modelscope download --model openbmb/VoxCPM-0.5B --local_dir "./models/VoxCPM-0.5B"

echo "lmdprogress:90"
conda_run_cmd modelscope download --model iic/speech_zipenhancer_ans_multiloss_16k_base

echo "lmdprogress:95"
conda_run_cmd modelscope download --model iic/SenseVoiceSmall

echo "lmdprogress:100"


